package middleware

import (
	"github.com/gin-gonic/gin"
	"server/model/common/response"
	sysService "server/service/system"
	"strconv"
	"strings"
)

// 拦截器
func CasbinHandler() gin.HandlerFunc {
	return func(c *gin.Context) {
		var permName string
		url := c.FullPath()
		if url != "" {
			url = string([]byte(url)[1:])
			permName = strings.Replace(url, "/", ".", -1)
		}
		//路由名为空直接跳过
		if permName == "" {
			c.Next()
			return
		}
		//权限数据读取
		permData, err := sysService.PermissionServiceApp.GetPermByName(permName)
		if err != nil {
			response.Forbidden("访问资源不在权限配置库中："+err.Error(), c)
			c.Abort()
			return
		}
		c.Set("permData", permData)
		//公共权限直接下一步
		if permData.IsPublic {
			c.Next()
			return
		}
		claims, _ := c.Get("claims")
		waitUse, ok := claims.(*sysService.CustomClaims)
		if !ok {
			response.Forbidden("用户识别无效", c)
			c.Abort()
			return
		}
		hasPerm, err := sysService.CasbinServiceApp.Casbin().Enforce(strconv.Itoa(int(waitUse.ID)), "admin", permName)
		if err != nil {
			response.Forbidden("权限判断错误："+err.Error(), c)
			c.Abort()
			return
		}
		if !hasPerm {
			response.Forbidden("权限不足"+permName, c)
			c.Abort()
			return
		}
		c.Next()
	}
}
